const EPub = require('epub');
const path = require('path');
const fs = require('fs').promises;

// 从epub文件中提取封面图片
const extractCoverFromEpub = async (epub) => {
  return new Promise((resolve, reject) => {
    epub.on('end', async () => {
      try {
        // 尝试从元数据中获取封面图片ID
        const coverId = epub.metadata.cover;
        if (coverId) {
          // 获取封面图片
          epub.getImage(coverId, async (error, img, mimeType) => {
            if (error) {
              reject(error);
              return;
            }

            // 生成唯一的文件名
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            const ext = mimeType.split('/')[1];
            const coverFileName = `cover-${uniqueSuffix}.${ext}`;
            const coverPath = path.join(process.env.COVER_PATH, coverFileName);

            // 保存封面图片
            await fs.writeFile(coverPath, img);
            resolve(coverPath);
          });
        } else {
          resolve(null); // 没有找到封面图片
        }
      } catch (error) {
        reject(error);
      }
    });

    epub.on('error', reject);
    epub.parse();
  });
};

// 解析epub文件
const parseEpub = (epubPath) => {
  return new Promise((resolve, reject) => {
    const epub = new EPub(epubPath);
    epub.parse();
    epub.on('end', () => resolve(epub));
    epub.on('error', reject);
  });
};

// 获取章节内容
const getChapterContent = (epub, chapterId) => {
  return new Promise((resolve, reject) => {
    const chapter = epub.flow[chapterId];
    if (!chapter) {
      reject(new Error('章节不存在'));
      return;
    }

    epub.getChapter(chapter.id, (error, content) => {
      if (error) {
        reject(error);
        return;
      }

      const chapterData = {
        content,
        title: chapter.title || `第${parseInt(chapterId) + 1}章`,
        prev: chapterId > 0 ? {
          id: parseInt(chapterId) - 1,
          title: epub.flow[parseInt(chapterId) - 1]?.title || `第${parseInt(chapterId)}章`
        } : null,
        next: parseInt(chapterId) < epub.flow.length - 1 ? {
          id: parseInt(chapterId) + 1,
          title: epub.flow[parseInt(chapterId) + 1]?.title || `第${parseInt(chapterId) + 2}章`
        } : null
      };

      resolve(chapterData);
    });
  });
};

module.exports = {
  extractCoverFromEpub,
  parseEpub,
  getChapterContent
};